package com.qpx.jxcpage.consumer;


import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Component
@RabbitListener(queues = "qpxTopic1")
@Slf4j
public class GoodsConsumer {


    @RabbitHandler
    public void getMessage(String msg, Channel channel, Message message) throws IOException {


        try {
            log.info("queue-confirm-test:收到消息：{}",msg);

            //处理业务逻辑 1000行代码
            Map<String,Object> map = JSON.parseObject(msg, Map.class);
            testGenerateHtml(map);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        } catch (Exception e) {
            if (message.getMessageProperties().getRedelivered()){
                log.info("拒绝处理消息。。。。。");
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            }else {
                log.info("消息出现异常。。。。进入队列重新发送.。。。。。。");
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            }
            e.printStackTrace();
        } finally {

        }
    }


    public void testGenerateHtml(Map<String, Object> map) throws IOException, TemplateException {
        //创建配置类
        Configuration configuration = new Configuration(Configuration.getVersion());
        //设置模板路径
        String classpath = this.getClass().getResource("/").getPath();
        configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
        //设置字符集
        //configuration.setDefaultEncoding("UTF‐8");
        //加载模板
        Template template = configuration.getTemplate("goods-12345.ftl");

        //静态化
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        //静态化内容
        System.out.println(content);
        InputStream inputStream = IOUtils.toInputStream(content);
        //输出文件
        FileOutputStream fileOutputStream = new FileOutputStream(new File("D:/goods/goods-12345.html"));
        int copy = IOUtils.copy(inputStream, fileOutputStream);
    }
}
